const { app, BrowserWindow, Menu, ipcMain } = require('electron');
const path = require('path');

let mainWindow;

function createWindow() {
    mainWindow = new BrowserWindow({
        width: 1200,
        height: 800,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: path.join(__dirname, '../preload.js'),
            disableBlinkFeatures: 'Autofill'
        },
        icon: path.join(__dirname, '../../public/vite.svg') // Use a default icon for now
    });

    // Load the appropriate URL
    if (process.env.VITE_DEV_SERVER_URL) {
        mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL);
        mainWindow.webContents.openDevTools();
    } else {
        mainWindow.loadFile(path.join(__dirname, '../../dist/index.html'));
    }

    // Create menu (simplified for now)
    const menu = Menu.buildFromTemplate([
        {
            label: 'File',
            submenu: [
                { label: 'Exit', click: () => { app.quit(); } }
            ]
        },
        // Add Debug menu in dev
        ...(process.env.VITE_DEV_SERVER_URL ? [{
            label: 'Debug',
            submenu: [
                { role: 'reload' },
                { role: 'forceReload' },
                { role: 'toggleDevTools' }
            ]
        }] : [])
    ]);

    Menu.setApplicationMenu(menu);

    return mainWindow;
}

function getMainWindow() {
    return mainWindow;
}

// 处理跳转到主页面的IPC调用
ipcMain.handle('go-to-main-page', async (event) => {
    const sourceWebContents = event.sender;
    const window = BrowserWindow.fromWebContents(sourceWebContents);

    if (window) {
        window.loadFile('index.html');
    }

    return { success: true };
});

// 处理打开工作台的IPC调用
ipcMain.on('open-workbench', (event, options = {}) => {
    const sourceWebContents = event.sender;
    const window = BrowserWindow.fromWebContents(sourceWebContents);

    if (window) {
        window.loadFile('pages/workbench.html').then(() => {
            if (options.activeTab) {
                window.webContents.send('activate-tab', options);
            }
        });
    }
});

module.exports = {
    createWindow,
    getMainWindow
};
